#define _CRT_SECURE_NO_WARNINGS
#include"heap.h"

void HpInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}
void Hpdestroy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}

void swap(HpDataType* a, int child, int parent)
{
	HpDataType tmp = a[child];
	a[child] = a[parent];
	a[parent] = tmp;
}

void adjustup(HpDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			swap(a, child, parent);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void Hppush(HP* php, HpDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HpDataType* tmp = (HpDataType*)realloc(php->a, sizeof(HpDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size++] = x;
	adjustup(php->a, php->size - 1);
}

void adjustdown(HpDataType* a, int parent, int size)
{
	int child = parent * 2 + 1;
	if (a[child] > a[child + 1])
	{
		child++;
	}
	while (child < size)
	{
		if (a[parent] > a[child])
		{
			swap(a, child, parent);
			parent = child;
			child = parent * 2 + 1;
			if (a[child] > a[child + 1])
			{
				child++;
			}
		}
		else
		{
			break;
		}
	}
}

void Hppop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	swap(php->a, php->size - 1, 0);
	php->size--;
	adjustdown(php->a, 0, php->size);
}
bool Hpempty(HP* php)
{
	assert(php);
	return php->a == NULL;
}

HpDataType Hptop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	return php->a[0];
}

int Hpsize(HP* php)
{
	assert(php);
	return php->size;
}
